package krow.dev.contest;

import java.util.ArrayList;
import java.util.List;

import krow.dev.contest.Constants.Category;
import krow.dev.contest.Constants.Invoke;
import krow.dev.contest.controller.DbOpenHelper;
import krow.dev.contest.controller.FavoriteListFactory;
import krow.dev.contest.model.FavoriteItem;
import krow.dev.contest.model.TabItem;
import krow.dev.contest.view.CategoryPageAdapter;
import krow.dev.contest.view.FavoriteListAdapter;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.astuetz.PagerSlidingTabStrip;

public class MainActivity extends FragmentActivity {

	private PagerSlidingTabStrip mPagerSlidingTabStrip;
	private ViewPager mViewPager;
	private CategoryPageAdapter mTabAdapter;

	private FavoriteListAdapter mFavoriteListAdapter;
	private FavoriteListFactory mFavoriteListFactory;
	//private FavoriteListHeaderWrapper mFavoriteListHeaderWrapper;

	private DbOpenHelper mDbOpenHelper;
	private Cursor mCursor;

	private View mEmptyView;
	private ListView mFavoriteListView;
	private DrawerLayout mDrawerLayout;
	private ViewGroup mFavoriteLayout;
	private ActionBarDrawerToggle mDrawerToggle;

	// private String[] navItems = { "즐겨찾기 리스트" };

	// private Drawable oldBackground = null;
	// private int currentColor = 0xFF666666;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// final int pageMargin = (int)
		// TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
		// getResources().getDisplayMetrics());
		// pager.setPageMargin(pageMargin);

		mDbOpenHelper = new DbOpenHelper(this);

		initializeView();

		initializeNevigationDrawer();

		requestFavorite();
	}

	private void initializeView() { // 슬라이딩탭 및 뷰페이저 부분

		List<TabItem> tabItemList = new ArrayList<TabItem>();
		TabItem tabItem = new TabItem();
		tabItem.setName(getString(R.string.menu_department));
		tabItem.setCategory(Category.DEPARTMENT);
		tabItemList.add(tabItem);

		tabItem = new TabItem();
		tabItem.setName(getString(R.string.menu_target));
		tabItem.setCategory(Category.TARGET);
		tabItemList.add(tabItem);

		tabItem = new TabItem();
		tabItem.setName(getString(R.string.menu_enterprise));
		tabItem.setCategory(Category.ENTERPRISE);
		tabItemList.add(tabItem);

		tabItem = new TabItem();
		tabItem.setName(getString(R.string.menu_prize));
		tabItem.setCategory(Category.PRIZE);
		tabItemList.add(tabItem);

		tabItem = new TabItem();
		tabItem.setName(getString(R.string.menu_benefits));
		tabItem.setCategory(Category.BENEFITS);
		tabItemList.add(tabItem);

		mTabAdapter = new CategoryPageAdapter(getSupportFragmentManager(), tabItemList);
		mViewPager = (ViewPager) findViewById(R.id.viewpager_contest);
		mViewPager.setAdapter(mTabAdapter);
		mPagerSlidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs_category);
		mPagerSlidingTabStrip.setViewPager(mViewPager);
		mPagerSlidingTabStrip.setIndicatorColor(Color.parseColor(getString(R.color.background_titlebar)));

	}

	private void initializeNevigationDrawer() { // 네비게이션드로어
		mFavoriteLayout = (ViewGroup) findViewById(R.id.layout_favorite);

		mFavoriteListAdapter = new FavoriteListAdapter(getApplicationContext());
		//mFavoriteListHeaderWrapper = new FavoriteListHeaderWrapper(getApplicationContext());
		//mFavoriteListHeaderWrapper.setName("위시리스트 목록");
		
		mFavoriteListView = (ListView) findViewById(R.id.lv_activity_main_nav_list);
		//mFavoriteListView.addHeaderView(mFavoriteListHeaderWrapper.getView());
		mFavoriteListView.addFooterView(getLayoutInflater().inflate(R.layout.footer_dummy, null));
		// mNaviListView.setEmptyView(findViewById(R.id.emptyview));

		// mNaviListView.setAdapter(new ArrayAdapter<String>(this,
		// android.R.layout.simple_list_item_1, navItems));
		mFavoriteListView.setAdapter(mFavoriteListAdapter);

		mFavoriteListAdapter.notifyDataSetChanged();
		mFavoriteListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
				if (view.getTag() == null) {
					return;
					}
				
				FavoriteItem favoriteItem = (FavoriteItem) view.getTag();

				Intent intent = new Intent(MainActivity.this, ContestDetailActivity.class);
				intent.putExtra(Invoke.KEY_TITLE, favoriteItem.getTitle());
				intent.putExtra(Invoke.KEY_DESCRIPTION, favoriteItem.getDescription());
				intent.putExtra(Invoke.KEY_URL, favoriteItem.getLink());
				startActivity(intent);
				overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);

				mDrawerLayout.closeDrawer(mFavoriteLayout); // 추가됨
					
			}
				
		});

		mFavoriteListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> adapter, View view, int position, long id) {
						// TODO Auto-generated method stub

				FavoriteItem favoriteItem = (FavoriteItem) view.getTag();
				mCursor = null;
				mDbOpenHelper.open();
				String x = null;
				String mCode = favoriteItem.getLink().toString();
				System.out.println(mCode);
				mCursor = mDbOpenHelper.getMatchURL(mCode);
				System.out.println(mCursor.getCount());
						
				while (mCursor.moveToNext()) {
							
					x = mCursor.getString(mCursor.getColumnIndex("url"));
						
				}
						
				if (x.length() > 0) {
							
					System.out.println("db에서 해당코드가 존재함");
					Toast.makeText(MainActivity.this, "위시리스트에서 제거되었습니다.", Toast.LENGTH_SHORT).show();
					mDbOpenHelper.deleteColumn(mCode);
					mDbOpenHelper.close();
					requestFavorite();
						
				}
						
				mCursor.close();
				checkFavoriteCount();
						
				return false;
					
			}
			
		});

		mDrawerLayout = (DrawerLayout) findViewById(R.id.dl_activity_main_drawer);
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer) {

			@Override
			public void onDrawerClosed(View drawerView) {
				super.onDrawerClosed(drawerView);
			}

			@Override
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
			}

		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		findViewById(R.id.layout_home).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				mDrawerLayout.openDrawer(mFavoriteLayout);

			}
		});
	}

	private void requestFavorite() {
		// Log.e("test", "url: " + url);
		System.out.println("팩토리 요청");

		mFavoriteListFactory = new FavoriteListFactory(this);
		mFavoriteListFactory.setCompletionListener(mBuildCompletionListener);
		mFavoriteListFactory.execute();

	}

	private void checkFavoriteCount(){
		
		if(mFavoriteListAdapter.getCount() > 0){
			mFavoriteListView.setVisibility(View.VISIBLE);
		}else{
			mFavoriteListView.setVisibility(View.GONE);
		}
	}
	
	private FavoriteListFactory.OnCompletionListener mBuildCompletionListener = new FavoriteListFactory.OnCompletionListener() {

		@Override
		public void onCompletion(List<FavoriteItem> favoriteItemList) {
			mFavoriteListAdapter.setFavoriteItemList(favoriteItemList);
			mFavoriteListAdapter.notifyDataSetChanged();
			System.out.println("온컴플리션리스너 카운트 - " + mFavoriteListAdapter.getCount());
			checkFavoriteCount();
		}
	};

	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		System.out.println("컨피겨레이션 체인지드");
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			System.out.println("온옵션아이템셀렉티드");
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onResume() {
		super.onResume();
		System.out.println("리쥼");
		requestFavorite();
	}

}
